package han.cirno.corrupt.provider

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import han.cirno.corrupt.data.DB

class DataProvider:ContentProvider() {
    companion object{
        const val CLASSES_CODE=0
        const val TERM_CODE=1
        const val EXAMS_CODE=2
    }

    private lateinit var uriMatcher:UriMatcher

    override fun onCreate(): Boolean{
        uriMatcher=UriMatcher(UriMatcher.NO_MATCH).apply {
            addURI("${context?.packageName}.data_provider","classes", CLASSES_CODE)
            addURI("${context?.packageName}.data_provider","terms", TERM_CODE)
            addURI("${context?.packageName}.data_provider","exams", EXAMS_CODE)
        }
        return runCatching { DB.getInstance()}.isSuccess
    }
    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        return when (uriMatcher.match(uri)) {
            CLASSES_CODE -> DB.getInstance().classEntryDao().getAll()
            EXAMS_CODE-> DB.getInstance().examDao().getAll()
            TERM_CODE-> DB.getInstance().classTableDao().getAll()
            else->null
        }
    }
    override fun getType(uri: Uri): String? {
        return when(uriMatcher.match(uri)){
            CLASSES_CODE->"vnd.android.cursor.dir/corrupt_classes"
            TERM_CODE->"vnd.android.cursor.dir/corrupt_terms"
            EXAMS_CODE->"vnd.android.cursor.dir/corrupt_exams"
            else->null
        }
    }
    override fun insert(uri: Uri, values: ContentValues?): Uri?=null
    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int=0
    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int=0
}